package com.wanxiang.commonlib.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.KeyEvent;

import com.wanxiang.commonlib.utils.LogUtils;

import org.greenrobot.eventbus.EventBus;

public class HomeWatcherReceiver extends BroadcastReceiver {
    private static final String TAG = "HomeWatcherReceiver";
    public static final String LOG_TAG = "HomeReceiver";
    public static final String SYSTEM_DIALOG_REASON_KEY = "reason";
    public static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
    public static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
    public static final String SYSTEM_DIALOG_REASON_LOCK = "lock";
    public static final String SYSTEM_DIALOG_REASON_ASSIST = "assist";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
            if (SYSTEM_DIALOG_REASON_HOME_KEY.equals(reason)) {
                // 短按Home键
                LogUtils.Logd(TAG,"t8短按Home键");
                //EventBus.getDefault().post(new KeyEvent(SYSTEM_DIALOG_REASON_HOME_KEY));
            } else if (SYSTEM_DIALOG_REASON_RECENT_APPS.equals(reason)) {
                // 长按Home键 或者 activity切换键
                LogUtils.Logd(TAG,"长按Home键");
               // EventBus.getDefault().post(new KeyEvent(SYSTEM_DIALOG_REASON_RECENT_APPS));
            } else if (SYSTEM_DIALOG_REASON_LOCK.equals(reason)) {
            } else if (SYSTEM_DIALOG_REASON_ASSIST.equals(reason)) {
                // samsung 长按Home键
            }

        }
    }

    private static HomeWatcherReceiver mHomeKeyReceiver = null;

    public static HomeWatcherReceiver registerHomeKeyReceiver(Context context) {
        if (mHomeKeyReceiver == null) {
            mHomeKeyReceiver = new HomeWatcherReceiver();
        }
        final IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        context.registerReceiver(mHomeKeyReceiver, homeFilter);
        return mHomeKeyReceiver;
    }

    public static void unregisterHomeKeyReceiver(Context context) {
        if (null != mHomeKeyReceiver) {
            try {
                context.unregisterReceiver(mHomeKeyReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }
}